<template>
  <span>
    <el-button type="text" icon="el-icon-upload" @click="export_in">{{ name }}</el-button>
    <el-dialog
      :title="title"
      :visible.sync="exportVisible"
      top="5vh"
      width="500px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :http-request="uploadfile"
        :auto-upload="false"
        :file-list="fileList"
        :on-remove="deletefile"
        :on-success="uploadSuccess"
        :limit="Number(limit)"
        :on-exceed="handleExceed"
        action="upload"
        drag
        multiple
      >
        <i class="el-icon-upload"/>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div align="right">
        <el-button @click="exportVisible = false">取 消</el-button>
        <el-button :loading="btnLoad" type="primary" @click="confirmExportIn()">确 定</el-button>
      </div>
    </el-dialog>
  </span>
</template>
<script>
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import SERVER from '@/api/server'
import axios from 'axios'
export default {
  name: 'Upload',
  props: {
    title: String,
    name: String,
    limit: [String, Number],
    billType: [String, Number],
    billId: [String, Number],
    datainputName: String,
    urlparams: Object,
    model: String,
    url: String
  },
  data() {
    return {
      exportVisible: false,
      btnLoad: false,
      count: 0,
      fileslength: 0,
      fileList: [],
      fileIdStr: '',
      fileUploadIdStr: ''
    }
  },
  computed: {
    action() {
      return `${SERVER[this.model]}` + this.url
    }
  },
  watch: {
    count: function(val) {
      // 上传成功文件数量，上传文件数量
      if (this.count === this.fileslength) {
        this.uploadbyurl()
      }
    }
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传 ${this.limit} 个文件!`)
    },
    uploadbyurl() {
      // 已上传，新上传文件id
      const params = this.fileIdStr.slice(2) + '##@' + this.fileUploadIdStr.slice(2)
      // 添加属性
      this.$set(this.urlparams, this.datainputName, params)
      console.log(this.urlparams)
      request
        .put(this.action, this.urlparams)
        .then(response => {
          this.$message({
            type: 'success',
            message: `上传成功`
          })
          this.exportVisible = false
        })
        .catch(({ err }) => {
          this.$message({
            type: 'error',
            message: `上传失败`
          })
        })
    },
    uploadSuccess(res, file, fileList) {
    },
    // 打开弹框
    export_in() {
      // 编辑 查询文件列表
      debugger
      if (this.billType !== undefined && this.billId !== undefined) {
        const queryurl = `${SERVER.DMSCLOUD_BASEDATA}/file/billFiles/${
          this.billType
        }/${this.billId}`
        const params = {
          fileType: Number(this.billType),
          billId: Number(this.billId)
        }
        request
          .get(queryurl, params)
          .then(response => {
            this.fileList = response.initialPreviewConfig
            if (this.fileList.length > 0) {
              this.fileList.forEach(el => (el.name = el.caption))
            }
          })
          .catch(({ err }) => {})
      }
      this.exportVisible = true
    },
    // 上传确认
    confirmExportIn() {
      const uploads = this.$refs['upload'].uploadFiles
      for (let i = 0; i < uploads.length; i++) {
        if (uploads[i].key) {
          // 已上传文件id拼接字符串
          this.fileIdStr += ',;' + uploads[i].key
        } else {
          // 新上传文件数量
          this.fileslength += 1
        }
      }
      console.log(this.fileIdStr)
      console.log(this.fileslength)
      if (this.fileslength === 0) {
        this.uploadbyurl()
      } else {
        this.$refs['upload'].submit()
      }
    },
    // 文件上传
    uploadfile(f) {
      const param = new FormData() // 创建form对象
      param.append('Authorization', getToken())
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      } // 添加请求头
      // 附件上传
      param.append('dmsFile', f.file)
      // 文件保存至服务器
      axios
        .post(`${SERVER.DMSCLOUD_BASEDATA}/file`, param, config)
        .then(response => {
          // 新上传文件id字符串
          this.fileUploadIdStr += ',;' + response.data.fileUploadId
          this.count += 1
        })
        .catch(({ err }) => {
          this.$message({
            type: 'error',
            message: `${f.file.name}上传失败`
          })
        })
    },
    // 文件删除
    deletefile(file, fileList) {
      if (file.key) {
        const deleurl = `${SERVER.DMSCLOUD_BASEDATA}/file/delete/${
          this.billType
        }/${file.key}`
        const params = {
          billType: Number(this.billType),
          fileId: Number(file.key)
        }
        request
          .post(deleurl, params)
          .then(response => {})
          .catch(({ err }) => {})
      }
    }
  }
}
</script>

